<?php
// 这是系统自动生成的公共文件
/*加密*/
function md5_hash($password)
{
    return md5(md5($password) . 'md5_salt_SmTRx');
}



/*生成base64二维码*/
function qrcode64($text)
{
    ob_start();//开启缓冲区
    \PHPQRCode\QRcode::png($text);
    $img = ob_get_contents();//获取缓冲区内容
    ob_end_clean();//清除缓冲区内容
    $imgInfo = 'data:image/png;base64,' . base64_encode($img);//转base64
    //return '<img src="data:image/png;base64,'.base64_encode($img).'" />';
    return $imgInfo;

}

/*生成订单号*/
function getOrderNo($str)
{
    return $str.date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}


if (!function_exists('array_get')) {
    function array_get($array, $key, $default = null)
    {
        if (is_null($key)) {
            return $array;
        }

        if (isset($array[$key])) {
            return $array[$key];
        }

        foreach (explode('.', $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return value($default);
            }

            $array = $array[$segment];
        }
        return $array;
    }
}

/**
 * 根据起点坐标和终点坐标测距离
 * @param  [array]   $from    [起点坐标(经纬度),例如:array(118.012951,36.810024)]
 * @param  [array]   $to    [终点坐标(经纬度)]
 * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
 * @param  [int]     $decimal   精度 保留小数位数
 * @return [string]  距离数值
 * $lat1、$lng1、$lat2、$lng2 是用来表示两个点的经纬度坐标的参数，
 * 其中 $lat1 和 $lat2 分别表示第一个点和第二个点的纬度，$lng1 和 $lng2 分别表示第一个点和第二个点的经度。
 * 在使用 Vincenty 公式计算两点间距离时，需要注意参数的顺序，
 * 一般按照 $lat1, $lng1, $lat2, $lng2 的顺序传入函数。
 */
if (!function_exists('get_distance')) {
    function get_distance($from, $to, $km = false, $decimal = 2)
    {
        if ($to[0] == 'undefined') {
            $to[0] = '113.065335';
        }
        if ($to[1] == 'undefined') {
            $to[1] = '28.252480';
        }
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;
        if ($km) {
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }
}




/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
if (!function_exists('getCity')) {
    function getCity($ip = '')
    {
        if ($ip == '') {
            $data = "IP地址定位失败";
        } else {
            $url = "https://api.ip138.com/ip/?ip=" . $ip . "&datatype=jsonp&token=2ecdda1a596b866203b4da236088153b";
            $ip = json_decode(file_get_contents($url));
            if ($ip->ret != 'ok') {
                return false;
            }
            $data = [];
            $data['country'] = $ip->data[0];
            $data['regionName'] = $ip->data[1];
            $data['city'] = $ip->data[2];
        }
        return $data;
    }
}


/**
 * 时间格式
 *
 */
if (!function_exists('dayname')) {
    function dayname($date)
    {
        if (is_int($date)) {
            $new_d = $date;  //传来的时间戳
        } else {
            $new_d = strtotime($date);  //传来的时间
        }
        $difference = $new_d - strtotime(date('Y-m-d'));
        $difference = floor($difference / 86400);
        $weekarray = array("周日", "周一", "周二", "周三", "周四", "周五", "周六"); //先定义一个数组
        if ($difference == 0) {
            $d = '今天';
        } elseif ($difference == 1) {
            $d = '明天';
        } elseif ($difference >= 2) {
            $d = $weekarray[date("w", $new_d)];
        } else {
            $d = $date;
        }
        return $d;
    }
}


/**
 * 树形结构
 */
if (!function_exists('tree')) {
    function getTreeList($data = [], $field = 'name')
    {
        $arr = [];
        foreach ($data as $k => $v) {
            $childlist = isset($v['childlist']) ? $v['childlist'] : [];
            unset($v['childlist']);
            $v[$field] = $v['spacer'] . ' ' . $v[$field];
            $v['haschild'] = $childlist ? 1 : 0;
            if ($v['id']) {
                $arr[] = $v;
            }
            if ($childlist) {
                $arr = array_merge($arr, getTreeList($childlist, $field));
            }
        }
        return $arr;
    }
}

/*生成树状图*/
function generateTree($array)
{
    $items = [];
    $tree = [];
    if (!empty($array) && is_array($array)) {
        foreach ($array as $key => $value) {
            $items[$value['id']] = $value;
        }
        foreach ($items as $key => $value) {
            if (isset($items[$value['pid']])) {
                $items[$value['pid']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
    }
    return $tree;
}


/**
 * 生日转年龄
 * @param $birth_year
 * @param $birth_month
 * @param $birth_day
 * @return false|int|string
 */
function getAgeByBirth($birthday)
{
    if (empty($birthday) || is_null($birthday)) {
        return 23;
    }
    $birthday_arr = explode('-', $birthday);
    $birth_year = $birthday_arr['0'];  //生日年
    $birth_month = $birthday_arr['1']; //生日月
    $birth_day = $birthday_arr['2'];  //生日日
    if (empty($birth_year) || empty($birth_month) || empty($birth_day)) {
        return 0;
    }
    $current_year = date('Y', time());
    $current_month = date('m', time());
    $current_day = date('d', time());
    if ($birth_year >= $current_year) {
        return 0;
    }
    $age = $current_year - $birth_year - 1;
    if ($current_month > $birth_month) {
        return $age + 1;
    } else if ($current_month == $birth_month && $current_day >= $birth_day) {
        return $age + 1;
    } else {
        return $age;
    }
}


/**
 * 秒 转  时分秒
 */
function secondsToTime($init)
{
    $hours = floor($init / 3600);
    $minutes = floor(($init / 60) % 60);
    $seconds = $init % 60;
    return "{$hours}时{$minutes}分{$seconds}秒";
}



//数组倒叙
function array_rsort($arr, $isvalues = false)
{
    if (is_array($arr)) {
        $flag = false;
        //一维数组
        if (count($arr) == count($arr, 1)) {
            $flag = true;
            $i = 0;
            //转换成二维数组
            foreach ($arr as $key => $value) {
                $a[$i]["okey"] = $key;
                $a[$i]["value"] = $value;
                $i++;
            }
            $arr = $a;
        } //多维数组
        else {
            //添加临时key值
            foreach ($arr as $key => $value) {
                $value["okey"] = $key;
                $array[] = $value;
            }
            $arr = $array;
        }

        //倒叙并还原key值
        $count = count($arr) - 1;
        for ($i = 0; $i < count($arr); $i++) {
            $b[$arr[$count]["okey"]] = $arr[$count];
            $count--;
        }

        //重构一维数组
        if ($flag == true) {
            foreach ($b as $key => $value) {
                if ($isvalues) {
                    $c[] = $value["value"];
                } else {
                    $c[$value["okey"]] = $value["value"];
                }
            }
        } //多维数组去除临时key值
        else {
            foreach ($b as $key => $value) {
                unset($value["okey"]);
                if ($isvalues) {
                    $c[] = $value;
                } else {
                    $c[$key] = $value;
                }
            }
        }
        return $c;
    }
}


// 定义最小二乘法函数
function least_squares($x, $y)
{
    $n = count($x);
    $sum_x = array_sum($x);
    $sum_y = array_sum($y);
    $sum_x2 = 0;
    $sum_xy = 0;
    for ($i = 0; $i < $n; $i++) {
        $sum_x2 += $x[$i] * $x[$i];
        $sum_xy += $x[$i] * $y[$i];
    }
    $slope = ($n * $sum_xy - $sum_x * $sum_y) / ($n * $sum_x2 - $sum_x * $sum_x);
    return $slope;
}


//求数据的平均斜率
function calculate_average_slope($slopes)
{
    $sum = 0;
    foreach ($slopes as $slope) {
        $sum += $slope;
    }
    return $sum / count($slopes);
}


// get请求
function curlGet($url)
{
    $ch = curl_init();
    $header = array();
    $header[] = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


// get请求
function curlPut($url)
{
    $ch = curl_init();
    $header = array();
    $header[] = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


//发送post请求
function curlPost($url,$data)
{
    $ch = curl_init();
    $params[CURLOPT_URL] = $url;    //请求url地址
    $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
    $params[CURLOPT_SSL_VERIFYPEER] = false;
    $params[CURLOPT_SSL_VERIFYHOST] = false;
    $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
    $params[CURLOPT_POST] = true;
    $params[CURLOPT_POSTFIELDS] = $data;
    curl_setopt_array($ch, $params); //传入curl参数
    $content = curl_exec($ch); //执行
    curl_close($ch); //关闭连接
    return $content;
}


function json_post($url, $data = NULL)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if(!$data){
        return 'data is null';
    }
    if(is_array($data))
    {
        $data = json_encode($data);
    }
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER,array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length:' . strlen($data),
        'Cache-Control: no-cache',
        'Pragma: no-cache'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    $errorno = curl_errno($curl);
    if ($errorno) {
        return $errorno;
    }
    curl_close($curl);
    return $res;

}


//计算坐标距离
function vincentyDistance($lat1, $lng1, $lat2, $lng2) {
    $a = 6378137; // 赤道半径（单位：米）
    $f = 1/298.257223563; // 扁率
    $b = (1 - $f) * $a; // 极半径
    $L = deg2rad($lng2 - $lng1); // 经差
    $U1 = atan((1 - $f) * tan(deg2rad($lat1))); // 标准纬度
    $U2 = atan((1 - $f) * tan(deg2rad($lat2)));
    $sinU1 = sin($U1);
    $sinU2 = sin($U2);
    $cosU1 = cos($U1);
    $cosU2 = cos($U2);
    $lambda = $L;
    $lambdaP = 2 * pi();
    $iterLimit = 20;

    while (abs($lambda - $lambdaP) > 1e-12 && $iterLimit-- > 0) {
        $sinLambda = sin($lambda);
        $cosLambda = cos($lambda);
        $sinSigma = sqrt(($cosU2 * $sinLambda) * ($cosU2 * $sinLambda) +
            ($cosU1 * $sinU2 - $sinU1 * $cosU2 * $cosLambda) *
            ($cosU1 * $sinU2 - $sinU1 * $cosU2 * $cosLambda));
        if ($sinSigma == 0) {
            return 0; // 重合的情况
        }
        $cosSigma = $sinU1 * $sinU2 + $cosU1 * $cosU2 * $cosLambda;
        $sigma = atan2($sinSigma, $cosSigma);
        $sinAlpha = $cosU1 * $cosU2 * $sinLambda / $sinSigma;
        $cosSqAlpha = 1 - $sinAlpha * $sinAlpha;
        if ($cosSqAlpha == 0) {
            $cos2SigmaM = 0; // 赤道上的情况
        } else {
            $cos2SigmaM = $cosSigma - 2 * $sinU1 * $sinU2 / $cosSqAlpha;
        }
        $C = $f / 16 * $cosSqAlpha * (4 + $f * (4 - 3 * $cosSqAlpha));
        $lambdaP = $lambda;
        $lambda = $L + (1 - $C) * $f * $sinAlpha *
            ($sigma + $C * $sinSigma *
                ($cos2SigmaM + $C * $cosSigma *
                    (-1 + 2 * $cos2SigmaM * $cos2SigmaM)));
    }
    if ($iterLimit == 0) {
        return null; // 没有收敛的情况
    }
    $uSq = $cosSqAlpha * ($a * $a - $b * $b) / ($b * $b);
    $A = 1 + $uSq / 16384 * (4096 + $uSq * (-768 + $uSq *
                (320 - 175 * $uSq)));
    $B = $uSq / 1024 * (256 + $uSq * (-128 + $uSq * (74 - 47 * $uSq)));
    $deltaSigma = $B * $sinSigma * ($cos2SigmaM + $B / 4 *
            ($cosSigma * (-1 + 2 * $cos2SigmaM * $cos2SigmaM) -
                $B / 6 * $cos2SigmaM * (-3 + 4 * $sinSigma * $sinSigma) *
                (-3 + 4 * $cos2SigmaM * $cos2SigmaM)));
    $s = $b * $A * ($sigma - $deltaSigma);
    return round($s); // 返回两点间的距离（单位：米）
}







/**
 * 时间格式
 *
 */
if(!function_exists('dayname')) {
    function dayname($date)
    {
        if(is_int($date)){
            $new_d = $date;  //传来的时间戳
        }else{
            $new_d = strtotime($date);  //传来的时间
        }
        $difference =$new_d - strtotime(date('Y-m-d'));
        $difference=floor($difference/86400);
        $weekarray=array("周日","周一","周二","周三","周四","周五","周六"); //先定义一个数组
        if ($difference == 0) {
            $d = '今天';
        } elseif ($difference == 1) {
            $d = '明天';
        } elseif ($difference >= 2) {
            $d=$weekarray[date("w",$new_d)];
        }else{
            $d=$date;
        }
        return $d;
    }
}


/**
 * 生成提现单号
 * @return string
 */
function createWithdrawNo(){
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}


function getYearsByZodiac($zodiac) {
    $startYear =1900; // 已知的起始年份
    $endYear = 2099; // 已知的结束年份
    $zodiacData = [
        'rat' => 0,
        'ox' => 1,
        'tiger' => 2,
        'rabbit' => 3,
        'dragon' => 4,
        'snake' => 5,
        'horse' => 6,
        'goat' => 7,
        'monkey' => 8,
        'rooster' => 9,
        'dog' => 10,
        'pig' => 11
    ];

    if(empty($zodiac)){
        $zodiac=array_rand($zodiacData);
    }

    if (array_key_exists($zodiac, $zodiacData)) {
        $zodiacIndex = $zodiacData[$zodiac];
        $years = [];
        for ($year = $startYear; $year <= $endYear; $year++) {
            if (($year - $startYear) % 12 === $zodiacIndex) {
                $years[] = $year;
            }
        }
        $age_arr=[];
        foreach ($years as $key=>$vo){
            $age=getAgeByBirth($years[$key].'-01-01');
            if($age>18 && $age<61){
                $age_arr[]=$vo;
            }
        }
        return $age_arr;
    } else {
        return [];
    }
}


//$distanceInKm   将距离转换为公里
function getwalkTime($distanceInKm){
    // 步行速度（公里/小时）
    $walkingSpeed = 5;
    // 计算步行时间
    $walkingTime = $distanceInKm / $walkingSpeed;
    // 转换为分钟
    $walkingTimeInMinutes = $walkingTime * 60;
    return $walkingTimeInMinutes;
}


/**
 * 生成邀请码
 * @param $userId  [用户ID]
 */
function rand_code($order_id)
{
    $chars = '0123456789';
    $num = strlen($chars);
    $str = '';
    while ($order_id > 0) {
        $mod = $order_id % $num;
        $order_id = ($order_id - $mod) / $num;
        $str = $chars[$mod] . $str;
    }
    // 不足用随机字符串补充，10表示邀请码邀请10位
    $str = str_pad($str, 6, createNonceStr(10 - strlen($str)), STR_PAD_LEFT);
    return $str;
}
function createNonceStr($length = 16)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}


/**
 * 最近7天的日期
 */
function sevenday(){
    for($i=0;$i<7;$i++){
        $dateArray[$i]['d']=date('d',strtotime(date('Y-m-d').'+'.$i.'day'));
        $dateArray[$i]['date']=date('m-d',strtotime(date('Y-m-d').'+'.$i.'day'));
        $dateArray[$i]['new_date']=date('Y-m-d',strtotime(date('Y-m-d').'+'.$i.'day'));
        $dateArray[$i]['name']=dayname(date('Y-m-d',strtotime(date('Y-m-d').'+'.$i.'day')));
    };
    return $dateArray;
}





function  getOrderNumber($string){
     return  $string.time().uniqid();
}




